package com.xianyun.smartpicturebackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.xianyun.smartpicturebackend.annotation.AuthCheck;
import com.xianyun.smartpicturebackend.common.BaseResponse;
import com.xianyun.smartpicturebackend.common.ResultUtils;
import com.xianyun.smartpicturebackend.constant.UserConstant;
import com.xianyun.smartpicturebackend.exception.BusinessException;
import com.xianyun.smartpicturebackend.exception.ErrorCode;
import com.xianyun.smartpicturebackend.manager.CosManage;
import com.xianyun.smartpicturebackend.manager.FileManage;
import com.xianyun.smartpicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author xianYun
 * @version 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private CosManage cosManage;
    @Resource
    private FileManage fileManage;

    /*
    @RequestPart 接受表单数据（multipart/form-data类型的数据）
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile) {
        //1. 接受用户上传的文件，这里@RequestPart("file")注解已经帮我们完成了
        if (multipartFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件不能为空");
        }
        String fileName = multipartFile.getOriginalFilename();//得到上传的文件名字
        String filePath = String.format("/test/%s", fileName);//存储临时文件的路径
        File tempFile = null;
        try {
            //创建一个空的临时文件
            tempFile = File.createTempFile(filePath, null);
            //将 MultipartFile 类型转为 File 类型
            //2. 将用户上传的文件写入临时文件
            multipartFile.transferTo(tempFile);//将临时文件转存到本地
            //3. 将临时文件上传到cos
            cosManage.putObject(filePath, tempFile);
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload failed, filePath : " + filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e);
        } finally {
            //注意：一定要删除临时文件
            if (tempFile != null) {
                boolean delete = tempFile.delete();
                if (!delete) {
                    log.error("tempFile delete failed, filePath：{}", tempFile.getAbsolutePath());
                }
            }
        }
    }

    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download")
    public void testDownLoad(String filepath, HttpServletResponse response) {
        COSObject cosObject = cosManage.getObject(filepath);
        COSObjectInputStream cosObjectInputStream = cosObject.getObjectContent();
        //响应头设置
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
        try {
            response.getOutputStream().write(IOUtils.toByteArray(cosObjectInputStream));
            response.getOutputStream().flush();//一定要刷新流
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (cosObjectInputStream != null) {
                    cosObjectInputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @PostMapping("/uploadT")
  public BaseResponse<String> uploadTest(@RequestPart("file") MultipartFile multipartFile){
      UploadPictureResult test = fileManage.uploadPicture(multipartFile, "test");
      return ResultUtils.success(test.getUrl());
  }
}
